package com.gxa.hotel.core.util;



import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;




@Component
public class RestUtils {

    private static RestTemplate restTemplate ;
    static {
        //OkHttp3ClientHttp性能比较好，需要引入jar
//        restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory);
        restTemplate = new RestTemplate();
    }

    public static Map postWithParams(String url, Map<String, String> headers, MultiValueMap params) throws Exception {

        //请求头（类型）
        HttpHeaders httpHeaders = new HttpHeaders();
        //指定了参数类型，对应java中的@Requestparam
        //MediaType.APPLICATION_JSON 对应java中的@Requestparam
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        if (headers!=null){
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                httpHeaders.set(entry.getKey(),entry.getValue());
            }
        }
        HttpEntity httpEntity=new HttpEntity(params,httpHeaders);
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);

        return map;
    }

    /**
     * 通过参数发起请求的重载方法
     * @param url 请求地址
     * @param params 请求方法
     * @return map
     */
    public static Map postWithParams(String url,MultiValueMap params){
        //请求头（类型）
        HttpHeaders httpHeaders = new HttpHeaders();
        //指定了参数类型，对应java中的@Requestparam
        //MediaType.APPLICATION_JSON 对应java中的@Requestparam
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity httpEntity=new HttpEntity(params,httpHeaders);
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);

        return map;
    }
}
